<template>
	<view class="imListWrapper">
		<!-- 企业头部 -->
		<view class="company" v-if="LoginType == 1">
			<u-search placeholder="搜索联系人" v-model="userSearch" @input="handleUserSearch"
				:show-action="false"></u-search>
		</view>
		<!-- 个人头部 -->
		<view class="personal" v-if="LoginType == 2">
			<view class="item" @click="handleJump('/personal/JobManagementIndex?navStatus=2')">
				<image src="@/im/static/img/listTop1.png"></image>
				<view class="text">谁看过我</view>
			</view>
			<view class="item" @click="handleJump('/personal/JobManagementIndex?navStatus=1')">
				<image src="@/im/static/img/listTop2.png"></image>
				<view class="text">我的投递</view>
			</view>
			<view class="item" @click="handleJump('/personal/CollectionIndex?navStatus=0')">
				<image src="@/im/static/img/listTop3.png"></image>
				<view class="text">我的收藏</view>
			</view>
			<view class="item" @click="handleJump('/personal/JobManagementIndex?navStatus=0')">
				<image src="@/im/static/img/listTop4.png"></image>
				<view class="text">面试通知</view>
			</view>
		</view>
		<!-- 聊天会话列表 -->
		<view :class="imListBoxHeightClass">
			<!-- <Loading v-if="loading"></Loading> -->
			<view class="imList">
				<view v-if="chatListAry.length > 0" style="height: 100%;">
					<scroll-view :scroll-y="isScroll" style="height: 100%;">
						<view class="topTips" v-if="LoginType == 1 && seeInfo.count > 0"
							@click="handleJump('/pages/im/seeList')">
							<view class="img">
								<image src="@/im/static/img/listTop5.png"></image>
							</view>
							<view class="text">
								<view class="t1">
									<view class="name">{{ seeInfo.resume_fullname }} 查看了您</view>
									<view class="time">{{ seeInfo.addtime | timeFilter }}</view>
								</view>
								<view class="t2">{{ seeInfo.count }}位人才查看</view>
							</view>
						</view>

						<view :class="item.chat_id == lastTopChatId ? 'imItem top' : 'imItem'"
							v-for="(item,index) in chatListAry" :key="item.chat_id" @click="handlejumpImShow(item)">
							<view class="imItemInner" :data-index="index" @touchstart="drawStart" @touchmove="drawMove"
								@touchend="drawEnd" :style="{transform:`translateX(-${item.right}rpx)`}">
								<!-- {{item.right}} -->
								<view class="imInfo clearfix">
									<view class="img">
										<view class="badge" v-if="item.new > 0"></view>
										<image :src="item.avatar" mode=""></image>
									</view>
									<!-- 个人聊天页面看到的列表应该是企业 -->
									<view class="companyText" v-if="LoginType == 2">
										<view class="t1 substring">
											<view class="name substring">{{ item.detail }}</view>
											<view class="time">{{ item.updatetime }}</view>
										</view>
										<view class="t2 substring">
											<text class="unread" v-if="item.new > 0">[未读]</text>
											{{ item.last_message }}
										</view>
									</view>
									<!-- 企业聊天页面看到的列表应该是个人 -->
									<view class="personalText" v-if="LoginType == 1">
										<view class="t1 substring">
											<view class="name substring">
												<text class="nameText">{{ item.nickname }}</text>
												<text class="job">{{ item.jobname }}</text>
											</view>
											<view class="time">{{ item.updatetime }}</view>
										</view>
										<view class="t2 substring">
											<text class="unread" v-if="item.new > 0">[未读]</text>
											{{ item.last_message }}
										</view>
									</view>
								</view>
								<view class="itemRight">
									<view class="imBtn">
										<view class="top" @click.stop="handleTop(item)">
											<image v-if="item.stick == 0" src="@/im/static/img/top.png"></image>
											<image v-else src="@/im/static/img/topAc.png"></image>
										</view>
										<view class="del" @click.stop="openDialog(item)">
											<image src="@/im/static/img/del.png"></image>
										</view>
									</view>
								</view>
							</view>
						</view>
					</scroll-view>
				</view>
				<!-- <Empty v-else></Empty> -->
			</view>
		</view>
		<BottomNav></BottomNav>
		<TopTips ref="TopTips"></TopTips>
		<!--  屏蔽提示弹窗 -->
		<Popup ref="isBlackDialog" title="系统提示" :showCancelButton="true" :isCloseBtn="false"
			:confirmBtnText="isBlackStatus == 1 ? '解除屏蔽' : '确定'" @confirm="handleIsRemoveBlack">
			<view style="padding:40rpx;">
				{{ isBlackDialogText }}
			</view>
		</Popup>
		<!-- 删除会话提示框 -->
		<Popup ref="delDialog" title="系统提示" @confirm="handleDel" :showCancelButton="true">
			<view style="padding:40rpx 0">
				确定删除此对话吗？
			</view>
		</Popup>
		<!-- 强制绑定微信公众号弹窗  -->
		<Popup class="bindWxWrapper" ref="bindWx" :maskCloseAble="false" title="系统提示" @confirm="handleImCheckBind">
			<view class="bindWx">
				<view class="title1">您当前未绑定微信，绑定后可发起聊天。</view>
				<view class="img">
					<image class="qrcode" :show-menu-by-longpress='true' :src="bindWxImg"></image>
				</view>
				<view class="title2">使用微信扫一扫，按提示快速绑定</view>
			</view>
		</Popup>
		<!-- 职聊功能未开启弹窗提示 -->
		<Popup ref="imDisabled" title="系统提示" :maskCloseAble="false" @confirm="handleDisabled">
			<view style="padding:40rpx 0">
				{{ imDisabledText }}
			</view>
		</Popup>
		<!-- 选择职位 -->
		<jobDialog ref="jobDialog" :istab="false" type="changejob" @handleChangeJob="handleChangeJob"
			:companyId="chatItem.companyid"></jobDialog>

		<!-- 简历完善度不足引导完善简历 -->
		<Popup ref="perfectResume" :showCancelButton="true" title="系统提示" @confirm="jumpResume">
			<view style="padding:20rpx 0">
				当前简历完善度不足请前去完善简历
			</view>
		</Popup>
	</view>
</template>

<script>
	import http from '@/utils/http'
	import api from '@/api'
	import {
		mapState,
		mapMutations,
		mapActions
	} from 'vuex';
	import {
		parseTime,
		formatTime
	} from '@/utils/index.js';
	import jobDialog from '@/im/components/jobDialog.vue';
	export default {
		data() {
			return {
				isScroll: true,
				// overflowWidth:256,
				overflowWidth: 200,
				loading: true,
				chatListAry: [],
				initChatListAry: [],
				// 是否在黑名单文字
				isBlackDialogText: '',
				// 是否黑名单状态
				isBlackStatus: 0,
				//点击用户数据
				chatItem: {},
				// 删除会话数据
				delItem: {},
				// 绑定二维码图片
				bindWxImg: '',
				// 职聊未开启提示语文字
				imDisabledText: '',
				// 置顶最后一个id 用于添加下边框
				lastTopChatId: '',
				// 查看信息
				seeInfo: {},
				// 搜索
				userSearch: '',
			};
		},
		components: {
			jobDialog
		},
		filters: {
			timeFilter(timestamp) {
				return formatTime(timestamp, '{y}-{m}-{d}', true);
			},
			interviewTimeFilter(timestamp) {
				return parseTime(timestamp, '{y}-{m}-{d} {h}:{i}');
			}
		},
		computed: {
			...mapState(['LoginType', 'imToken', 'chatId', 'chatList', 'messageList', 'IsUpdataChatList']),
			imListBoxHeightClass() {
				if (this.LoginType == 1 && this.LoginType != 0) {
					if (uni.getSystemInfoSync().platform == 'android') {
						return 'imListBox companyImListBoxAndroid'
					} else {
						return 'imListBox companyImListBoxIos'
					}

				} else {
					if (uni.getSystemInfoSync().platform == 'android') {
						return 'imListBox personalImListBoxAndroid'
					} else {
						return 'imListBox personalImListBoxIos'
					}
				}
			}
		},
		onShow() {
			// if (this.imToken != '') {
			this.imWindowGlobal();
			// }
			if (this.LoginType == 1) {
				this.getSeeCount();
			}
			// this.getChatLists({
			// 	url: api.chatList
			// });
			this.initWebSocket()
		},
		watch: {
			imToken: {
				handler(newVal, oldVal) {
					if (newVal != oldVal) {
						this.imWindowGlobal();
					}
				},
				deep: true,
				immediate: true
			},
			userSearch(val) {
				if (val == '') {
					this.lastTopChatId = '';
				}
			},
			chatList(val, oldVal) {
				this.chatListAry = val;
				this.initChatListAry = val;
				this.chatListAry.forEach((item, index) => {
					if (item.stick == 1) {
						this.lastTopChatId = item.chat_id;
					}
					//修复清空未读消息
					// if (item.chat_id == this.chatItem.chat_id) {
					// 	item.new = 0;
					// }
					this.$set(item, 'right', 0)
				});
				this.handleUserSearch();
				this.$nextTick(() => {
					this.loading = false;
				});
			},
			messageList(newValue, oldValue) {
				this.getChatLists({
					url: api.chatList
				})
			},
			IsUpdataChatList(newValue, oldValue) {
				this.getChatLists({
					url: api.chatList
				})
			}
		},
		methods: {
			...mapActions(['getChatLists', 'initWebSocket']),
			...mapMutations(['setImChatId']),
			// 路径跳转
			handleJump(url) {
				uni.navigateTo({
					url: url
				});
			},
			// 跳转聊天详情
			handlejumpImShow(chatItem) {
				this.chatItem = chatItem;
				this.chatListAry.forEach(item => {
					if (item.chat_id == chatItem.chat_id) {
						item.new = 0;
					}
				});
				this.setImChatId(chatItem.chat_id);
				// 检测是否在黑名单中
				this.isBlackList(chatItem);
			},
			// 检测用户是否在黑名单中
			isBlackList(chatItem) {
				http.post(api.check_blacklist, {
					token: this.imToken,
					chatid: chatItem.chat_id
				}).then(res => {
					if (res.data.code == 200) {
						// res.data.data
						// 0 没有屏蔽
						// 1 您已屏蔽对方，如需继续聊天请先解除屏蔽
						// 2 您已被对方加入黑名单，无法继续与TA聊天哦
						if (res.data.data != 0) {
							// 提示用户被屏蔽
							this.isBlackStatus = res.data.data;
							this.isBlackDialogText = res.data.message;
							this.$refs.isBlackDialog.open();
						} else {
							// 检测是否选择过职位
							this.isSelectJob();
						}
					}
				});
			},
			// 移除黑名单
			handleIsRemoveBlack() {
				if (this.isBlackStatus == 1) {
					http.post(api.del_blacklist, {
						token: this.imToken,
						chatid: this.chatItem.chat_id
					}).then(res => {
						if (res.data.code == 200) {
							// 检测是否选择过职位
							this.isSelectJob();
						}
					});
				}
			},
			// 是否选择过职位
			isSelectJob() {
				http.post(api.im_job_detail, {
					jobid: this.chatItem.jobid
				}).then(res => {
					if (res.data.code == 200) {
						let {
							next
						} = res.data.data;
						// 选择职位 
						if (next == 'choose_job') {
							this.$refs.jobDialog.getJobList();
						} else {
							// 进入聊天页面
							this.jumpImShow();
						}
					}
				});
			},
			// 跳转聊天详情页面
			jumpImShow() {
				let showParams = {
					jobname: this.chatItem.jobname,
					chatid: this.chatItem.chat_id,
					name: this.LoginType == 1 ? this.chatItem.nickname : this.LoginType == 2 ? this.chatItem.detail :
						'', //1-企业  2-个人
					stick: this.chatItem.stick,
					jobid: this.chatItem.jobid,
					resumeid: this.chatItem.resumeid,
					companyid: this.chatItem.companyid
				};
				uni.navigateTo({
					url: '/im/imShow',
					success(res) {
						res.eventChannel.emit('acceptDataFromOpenerPage', showParams)
					}
				});
			},
			// 切换职位返回
			handleChangeJob(changeJob) {
				let currentChat = this.chatListAry.filter(item => {
					return this.chatId == item.chat_id;
				})[0];
				this.chatItem = currentChat;
				this.jumpImShow();
			},
			// 获取列表
			/**
			 * 即时通讯进入界面时全局检测
			 * disabled 不能使用功能
			 * bind_weixin绑定微信
			 * complete_resume完善简历
			 * 空字符串 正常使用
			 * choose_job选择职位
			 * pay需要购买增值服务，触屏是快捷支付
			 */
			imWindowGlobal() {
				http.get(api.im_window_global).then(res => {
					if (res.data.code == 200) {
						if (res.data.data.next == '') {
							this.lastTopChatId = '';
							if (this.imToken == '') {
								this.getImToken()
							} else {
								this.getChatLists({
									url: api.chatList
								})
							}
							return false;
						}
						if (res.data.data.next == 'bind_weixin') {
							// 绑定微信
							// #ifdef MP-WEIXIN
							this.getBIndWximage();
							// #endif
							// #ifdef MP-TOUTIAO
							this.lastTopChatId = '';
							this.getChatLists({
								url: api.chatList
							});
							// #endif
							return false;
						}
						if (res.data.data.next == 'complete_resume') {
							// 编辑简历
							this.$nextTick(() => {
								this.loading = false;
							});
							// 打开完善简历弹窗提示
							this.$refs.perfectResume.open();
							return false;
						}
						if (res.data.data.next == 'disabled') {
							// 职聊未开启
							this.imDisabledText = res.data.message;
							this.$refs.imDisabled.open();
							this.$nextTick(() => {
								this.loading = false;
							});
							return false;
						}
					}
				});
			},
			// 完善简历跳转
			jumpResume() {
				uni.navigateTo({
					url: '/pages/personal/resumeIndex/resumeIndex'
				});
			},
			// 获取微信绑定二维码图片
			getBIndWximage() {
				http.get(api.get_qrcode, {
					type: 'bind_weixin'
				}).then(res => {
					if (res.data.code == 200) {
						this.bindWxImg = res.data.data;
						this.$nextTick(() => {
							this.loading = false;
							this.$refs.bindWx.open();
						});
					}
				});
			},
			// 置顶
			handleTop(item) {
				http.post(api.chatStick, {
					token: this.imToken,
					chat_id: item.chat_id,
					stick: item.stick == 0 ? 1 : 0
				}).then(res => {
					if (res.data.code == 200) {
						let title = item.stick == 0 ? '置顶成功' : '取消成功';
						this.$refs.TopTips.show({
							title: title,
							type: 'success',
						})
						// 更新列表
						this.lastTopChatId = '';
						this.getChatLists({
							url: api.chatList
						});
					}
				});
			},
			// 打开对话提示框
			openDialog(item) {
				this.delItem = item;
				this.$refs.delDialog.open();
			},
			// 删除会话
			handleDel() {
				http.post(api.imRemoveChat, {
					token: this.imToken,
					chat_id: this.delItem.chat_id
				}).then(res => {
					if (res.data.code == 200) {
						this.$refs.TopTips.show({
							title: res.data.message,
							type: 'success',
						})
						// 更新列表
						this.lastTopChatId = '';
						this.getChatLists({
							url: api.chatList
						});
					}
				});
			},
			// 检测是否绑定公众号
			handleImCheckBind() {
				http.get(api.imCheckBind).then(res => {
					if (res.data.data != 0) {
						this.imWindowGlobal();
					} else {
						// 1企业 2个人
						if (this.LoginType == 1) {
							uni.navigateTo({
								url: '/pages/company/companyIndex'
							});
						} else {
							uni.navigateTo({
								url: '/pages/personal/personalIndex'
							});
						}
					}
				});
			},
			// 职聊功能未开启弹窗
			handleDisabled() {
				if (this.LoginType == 1) {
					uni.navigateTo({
						url: '/company/CompanyIndex'
					});
				} else {
					uni.navigateTo({
						url: '/personal/PersonalIndex'
					});
				}
			},
			// 获取最新的 查看人信息
			getSeeCount() {
				http.get(api.countViewBe).then(res => {
					if (res.data.code == 200) {
						this.seeInfo = {
							resume_fullname: res.data.resume_fullname,
							count: res.data.count,
							addtime: res.data.addtime
						};
					}
				});
			},
			// 搜索
			handleUserSearch(e) {
				let chatListAry = this.initChatListAry;
				let newchatListAry = [];
				if (this.userSearch != '') {
					for (let i in chatListAry) {
						if (chatListAry[i].nickname.indexOf(this.userSearch) == -1) {
							chatListAry[i].hide = false;
						} else {
							chatListAry[i].hide = true;
							newchatListAry.push(chatListAry[i]);
						}
					}
					this.chatListAry = newchatListAry;
				} else {
					for (let i in chatListAry) {
						chatListAry[i].hide = true;
					}
					this.chatListAry = chatListAry;
				}
			},
			drawStart(e) {
				var touch = e.touches[0];
				for (var index in this.chatListAry) {
					this.$set(this.chatListAry[index], 'right', 0)
				}
				this.startX = touch.clientX;
			},
			drawMove(e) {
				var touch = e.touches[0];
				var index = e.currentTarget.dataset.index
				var item = this.chatListAry[index];
				var disX = this.startX - touch.clientX;
				// this.$set(this.chatListAry[index],'right',disX)
				if (disX >= 2) {
					if (disX > this.overflowWidth) {
						disX = this.overflowWidth;
					}
					this.isScroll = false;
					this.$set(this.chatListAry[index], 'right', disX)
				} else {
					this.isScroll = true;
					this.$set(this.chatListAry[index], 'right', 0)
				}
			},
			drawEnd(e) {
				var item = this.chatListAry[e.currentTarget.dataset.index];
				var index = e.currentTarget.dataset.index
				if (item.right >= this.overflowWidth / 2) {
					this.$set(this.chatListAry[index], 'right', this.overflowWidth)
					this.isScroll = true;
				} else {
					this.isScroll = true;
					this.$set(this.chatListAry[index], 'right', 0)
				}
			},
		}
	};
</script>

<style lang="scss" scoped>
	.imListWrapper {
		width: 100%;
		height: 100%;

		.hdLeft {
			color: #fff;
			font-size: 46rpx;
			font-weight: 500;
		}

		.hdMsg {
			width: 30rpx;
			height: 38rpx;
			margin-left: 35rpx;
			margin-top: 14rpx;

			image {
				width: 100%;
				height: 100%;
				display: block;
			}
		}

		.company {
			padding: 20rpx 36rpx;

			::v-deep.content-clear-icon {
				padding-left: 30rpx;
			}

			::v-deep .uni-easyinput__content {
				background: #f7f4f8 !important;
				border-radius: 50rpx !important;
			}

			::v-deep .is-input-border {
				border: none !important;
			}
		}

		.personal {
			display: flex;
			align-items: center;
			justify-content: center;
			border-bottom: 1rpx solid #ededed;

			.item {
				flex: 1;
				padding: 30rpx 0;
				text-align: center;

				image {
					width: 95rpx;
					height: 95rpx;
				}
			}

			.text {
				font-size: 28rpx;
				color: #333;
			}
		}

		// 企业用户列表高度
		.companyImListBoxIos {
			height: calc(100% - 120rpx - 96rpx);
			background: #fff;
		}

		.companyImListBoxAndroid {
			height: calc(100% - 120rpx - 88rpx);
		}

		// 个人用户列表高度
		.personalImListBoxIos {
			height: calc(100% - 120rpx - 228rpx);
			background: #faf7fa;
		}

		.personalImListBoxAndroid {
			height: calc(100% - 120rpx - 192rpx);
		}

		.imListBox {
			.imList {
				height: 100%;

				.topTips {
					display: flex;
					align-items: center;
					padding: 30rpx 36rpx;

					.img {
						flex-shrink: 0;
						width: 91rpx;
						height: 91rpx;
						margin-right: 28rpx;
						border-radius: 50%;

						image {
							width: 100%;
							height: 100%;
							border-radius: 50%;
						}
					}

					.text {
						flex-shrink: 0;
						width: 350rpx;

						.t1 {
							display: flex;
							margin-bottom: 10rpx;
							font-weight: bold;
							align-items: center;

							.name {
								color: #3e3b3f;
								font-size: 28rpx;
								flex-shrink: 0;
								width: 410rpx;
							}

							.time {
								color: #666;
								font-size: 24rpx;
								flex-shrink: 0;
								width: 140rpx;
								text-align: right;
								font-weight: normal;
							}
						}

						.t2 {
							color: #999;
							font-size: 28rpx;
						}
					}
				}

				.imItem {
					background: #fff;
					overflow: hidden;

					&.top {
						border-bottom: 10rpx solid #f5f5f5;
					}

					.imItemInner {
						white-space: nowrap;
						display: flex;
						flex-wrap: nowrap;
						align-items: center;
					}

					.imInfo {
						display: flex;
						align-items: center;
						padding: 30rpx 36rpx;

						.img {
							flex-shrink: 0;
							// float: left;
							width: 91rpx;
							height: 91rpx;
							margin-right: 28rpx;
							position: relative;

							.badge {
								position: absolute;
								right: 0rpx;
								top: 0rpx;
								width: 20rpx;
								height: 20rpx;
								background: #ff4c56;
								border-radius: 50%;
								display: block;
								z-index: 555;
							}

							image {
								width: 100%;
								height: 100%;
								border-radius: 50%;
							}
						}

						.companyText {
							flex-shrink: 0;
							width: 565rpx;

							.t1 {
								display: flex;
								margin-bottom: 10rpx;

								.name {
									flex-shrink: 0;
									width: 400rpx;
									color: #333033;
									font-size: 30rpx;
									font-weight: 300;
								}

								.time {
									flex-shrink: 0;
									width: 140rpx;
									margin-left: 20rpx;
									color: #666;
									font-size: 24rpx;
									text-align: right;
								}
							}

							.t2 {
								.unread {
									color: #9f9c9f;
									font-size: 28rpx;
									margin-right: 10rpx;
								}

								color: #999;
								font-size: 28rpx;
							}
						}

						.personalText {
							flex-shrink: 0;
							width: 565rpx;

							.t1 {
								display: flex;
								margin-bottom: 10rpx;

								.name {
									flex-shrink: 0;
									width: 400rpx;

									.nameText {
										color: #333;
										font-size: 32rpx;
										font-weight: 400;
										margin-right: 20rpx;
									}

									.job {
										color: #ccc9cd;
										font-size: 28rpx;
									}
								}

								.time {
									flex-shrink: 0;
									width: 140rpx;
									margin-left: 20rpx;
									color: #666;
									font-size: 24rpx;
									text-align: right;
								}
							}

							.t2 {
								color: #999;
								font-size: 28rpx;
								width: 450rpx;

								.unread {
									margin-right: 10rpx;
									color: #939094;
									font-size: 28rpx;
								}
							}
						}
					}


					.itemRight {
						padding: 30rpx 0;

						.imBtn {
							display: flex;
							align-items: center;
							justify-content: center;
							padding-right: 36rpx;

							.del {
								flex-shrink: 0;
								width: 69rpx;
								height: 69rpx;

								image {
									width: 100%;
									height: 100%;
								}
							}

							.top {
								flex-shrink: 0;
								width: 69rpx;
								height: 69rpx;
								margin-right: 30rpx;

								image {
									width: 100%;
									height: 100%;
								}
							}
						}
					}

				}
			}
		}

		.bindWxWrapper {
			::v-deep.dialogContent {
				padding: 16rpx 40rpx 52rpx;
			}

			.bindWx {
				padding: 40rpx 0;

				.title1 {
					color: #646566;
					font-size: 26rpx;
				}

				.img {
					width: 240rpx;
					height: 240rpx;
					margin: 20rpx auto;

					.qrcode {
						width: 100%;
						height: 100%;
					}
				}

				.title2 {
					color: #646566;
					font-size: 26rpx;
				}
			}
		}
	}
</style>